package com.lzy.ninegrid;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;

import java.util.ArrayList;
import java.util.List;

public class NineGridView extends ViewGroup {
    /**
     * 填充模式，类似于微信
     */
    public static final int MODE_FILL = 0;
    /**
     * 网格模式，类似于QQ，4张图会 2X2布局
     */
    public static final int MODE_GRID = 1;
    private static final String TAG = "NineGridView";

    /**
     *  全局的图片加载器
     */
    private static ImageLoader mImageLoader;
    /**
     *  单张图片时的最大大小,单位dp
     */
    private int singleImageSize = 230;
    /**
     *  单张图片的宽高比(宽/高
     */
    private float singleImageRatio = 1.0f;
    /**
     *  最大显示的图片数
     */
    private int maxImageSize = 9;
    /**
     *  宫格间距，单位dp
     */
    private int gridSpacing = 3;
    /**
     *  默认使用fill模式
     */
    private int mode = MODE_FILL;

    /**
     *  列数
     */
    private int columnCount;
    /**
     *  行数
     */
    private int rowCount;
    /**
     *  宫格宽度
     */
    private int gridWidth;
    /**
     *  宫格高度
     */
    private int gridHeight;

    private List<ImageView> imageViews;
    private List<ImageInfo> mImageInfo;
    private NineGridViewAdapter mAdapter;

    /**
     * 自加属性
     **/

    /**
     * 单张图片最小高度
     **/
    private int singleImageMinHeight = 500;
    /**
     * 单张图片最小宽度
     **/
    private int singleImageMinWidth = 500;
    /**
     * 单张图片最大高度
     **/
    private int singleImageMaxHeight = 700;
    /**
     * 单张图片最大宽度
     **/
    private int singleImageMaxWidth = 600;

    public NineGridView(Context context) {
        this(context, null);
    }

    public NineGridView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NineGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        gridSpacing = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, gridSpacing, dm);
        singleImageSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, singleImageSize, dm);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.NineGridView);
        gridSpacing = (int) a.getDimension(R.styleable.NineGridView_ngv_gridSpacing, gridSpacing);
        singleImageSize = a.getDimensionPixelSize(R.styleable.NineGridView_ngv_singleImageSize, singleImageSize);
        singleImageRatio = a.getFloat(R.styleable.NineGridView_ngv_singleImageRatio, singleImageRatio);
        maxImageSize = a.getInt(R.styleable.NineGridView_ngv_maxSize, maxImageSize);
        mode = a.getInt(R.styleable.NineGridView_ngv_mode, mode);
        a.recycle();

        imageViews = new ArrayList<>();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = 0;
        int totalWidth = width - getPaddingLeft() - getPaddingRight();
        if (mImageInfo != null && mImageInfo.size() > 0) {
            if (mImageInfo.size() == 1) {
                int imageHeight = mImageInfo.get(0).getImageViewHeight();
                int imageWidth = mImageInfo.get(0).getImageViewWidth();
                //原尺寸高宽比
                float hwRatio = imageHeight * 1.0f / imageWidth;
                gridWidth = singleImageSize > totalWidth ? totalWidth : singleImageSize;
                gridHeight = (int) (gridWidth / singleImageRatio);
                //矫正图片显示区域大小，不允许超过最大显示范围
//                if (gridHeight > singleImageSize) {
//                    float ratio = singleImageSize * 1.0f / gridHeight;
//                    gridWidth = (int) (gridWidth * ratio);
//                    gridHeight = singleImageSize;
//                }
                //图片高度大于宽度
                if (imageHeight > imageWidth) {
                    if (imageHeight > singleImageMaxHeight) {
                        gridHeight = singleImageMaxHeight;
                        gridWidth = (int) (singleImageMaxHeight / hwRatio);
                        if (gridWidth < singleImageMinWidth) {
                            //避免图片展示过窄
                            gridWidth = singleImageMinWidth;
                        }
                    } else if (imageHeight < singleImageMinHeight) {
                        gridHeight = singleImageMinHeight;
                        gridWidth = (int) (singleImageMinHeight / hwRatio);
                    } else {
                        gridHeight = imageHeight;
                        gridWidth = imageWidth;
                    }
                    //宽度大于高度
                } else {
                    if (imageWidth > singleImageMaxWidth) {
                        gridWidth = singleImageMaxWidth;
                        gridHeight = (int) (gridWidth * hwRatio);
                    } else if (imageWidth < singleImageMaxWidth) {
                        gridWidth = singleImageMinWidth;
                        gridHeight = (int) (singleImageMinWidth * hwRatio);
                    } else {
                        gridWidth = imageWidth;
                        gridHeight = imageHeight;
                    }
                }
                width = gridWidth + getPaddingLeft() + getPaddingRight();
                height = gridHeight + getPaddingTop() + getPaddingBottom();
            }
//            else if (mImageInfo.size() == 2 || mImageInfo.size() == 4) {
//                gridWidth = gridHeight = (totalWidth - gridSpacing) / 2;
//                width = gridWidth * 2 + gridSpacing + getPaddingLeft() + getPaddingRight();
//                height = gridHeight * rowCount + gridSpacing + getPaddingTop() + getPaddingBottom();
//            }
            else {
//                gridWidth = gridHeight = (totalWidth - gridSpacing * (columnCount - 1)) / columnCount;
                //这里无论是几张图片，宽高都按总宽度的 1/3
                gridWidth = gridHeight = (totalWidth - gridSpacing * 2) / 3;
                width = gridWidth * columnCount + gridSpacing * (columnCount - 1) + getPaddingLeft() + getPaddingRight();
                height = gridHeight * rowCount + gridSpacing * (rowCount - 1) + getPaddingTop() + getPaddingBottom();
            }

        }
        setMeasuredDimension(width, height);
    }

    /**
     * 绘制九宫格子视图
     *
     * @param changed 是否改变
     * @param l       坐标
     * @param t       坐标
     * @param r       坐标
     * @param b       坐标
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (mImageInfo == null) {
            return;
        }
        int childrenCount = mImageInfo.size();
        for (int i = 0; i < childrenCount; i++) {
            //子视图是imageView
            ImageView childrenView = (ImageView) getChildAt(i);
            //SubsamplingScaleImageView longchildrenView=(SubsamplingScaleImageView) getChildAt(i);
            int rowNum = i / columnCount;
            int columnNum = i % columnCount;
            int left = (gridWidth + gridSpacing) * columnNum + getPaddingLeft();
            int top = (gridHeight + gridSpacing) * rowNum + getPaddingTop();
            int right = left + gridWidth;
            int bottom = top + gridHeight;
            childrenView.layout(left, top, right, bottom);
            // longchildrenView.layout(left, top, right, bottom);
            if (mImageLoader != null) {
                //原来是0
                ImageInfo imageInfo = mImageInfo.get(i);
                //??????===================================
                int height = imageInfo.getImageHeight();
                int width = imageInfo.getImageWidth();
                //??????===================================
                int scale;
                if (width != 0) {
                    scale = height / width;
                } else {
                    scale = 1;
                }
                width = 600;
                height = 600 * scale;
                boolean ifLong = imageInfo.getImageHeight() > 5000 && imageInfo.getImageHeight() / imageInfo.getImageWidth() >= 2;
                String thumbnailUrl = mImageInfo.get(i).getThumbnailUrl();
                if (ifLong) {
                    mImageLoader.onDisplayImage(
                            getContext(),
                            childrenView,
                            thumbnailUrl,
                            width,
                            height,
                            3020);
                    Log.d(TAG, "是长图 " + thumbnailUrl);
                } else {
                    mImageLoader.onDisplayImage(
                            getContext(),
                            childrenView,
                            thumbnailUrl,
                            width,
                            height
                    );
                    Log.d(TAG, "正常图 " + thumbnailUrl);
                }
              /*  Log.i(TAG,"图片尺寸"+imageInfo.getImageWidth()+" "+imageInfo.getImageHeight()
                +" "+imageInfo.getImageViewWidth()+" "+imageInfo.getImageViewHeight());*/
            } else {
                Log.d(TAG, "全局的图片加载器为空");
            }
        }
    }

    /**
     * 设置适配器
     */
    public void setAdapter(@NonNull NineGridViewAdapter adapter) {
        mAdapter = adapter;
        List<ImageInfo> imageInfo = adapter.getImageInfo();

        if (imageInfo == null || imageInfo.isEmpty()) {
            setVisibility(GONE);
            return;
        } else {
            setVisibility(VISIBLE);
        }

        int imageCount = imageInfo.size();
        if (maxImageSize > 0 && imageCount > maxImageSize) {
            imageInfo = imageInfo.subList(0, maxImageSize);
            //再次获取图片数量
            imageCount = imageInfo.size();
        }

        //默认是3列显示，行数根据图片的数量决定
        rowCount = imageCount / 3 + (imageCount % 3 == 0 ? 0 : 1);
        columnCount = 3;
        //grid模式下，显示4张使用2X2模式
        if (mode == MODE_GRID) {
            if (imageCount == 4) {
                rowCount = 2;
                columnCount = 2;
            }
        }

        //保证View的复用，避免重复创建
        if (mImageInfo == null) {
            for (int i = 0; i < imageCount; i++) {
                ImageView iv = getImageView(i);
                if (iv == null) {
                    Log.i(TAG,"视图为空"+iv.getDrawable());
                    return;
                }else {
                    addView(iv, generateDefaultLayoutParams());
                }
            }
        } else {
            int oldViewCount = mImageInfo.size();
            if (oldViewCount > imageCount) {
                removeViews(imageCount, oldViewCount - imageCount);
            } else if (oldViewCount < imageCount) {
                for (int i = oldViewCount; i < imageCount; i++) {
                    ImageView iv = getImageView(i);
                    if (iv == null) {
                        return;
                    }
                    addView(iv, generateDefaultLayoutParams());
                }
            }
        }
        //修改最后一个条目，决定是否显示更多
        if (adapter.getImageInfo().size() > maxImageSize) {
            View child = getChildAt(maxImageSize - 1);
            if (child instanceof NineGridViewWrapper) {
                NineGridViewWrapper imageView = (NineGridViewWrapper) child;
                imageView.setMoreNum(adapter.getImageInfo().size() - maxImageSize);
            }
        }
        //写入图片类型，
        for (int i = 0; i < imageInfo.size(); i++) {
            ImageInfo info = imageInfo.get(i);
            String fileName = NineGridViewImgUtils.getFileName(info.getBigImageUrl());
            String type = fileName.substring(fileName.lastIndexOf(".") + 1);
            View child = getChildAt(i);
            NineGridViewWrapper imageView = (NineGridViewWrapper) child;

            //如果是长图，将图片类型写为长图
            Boolean ifLong = imageInfo.get(i).getImageHeight() > 5000 && imageInfo.get(i).getImageHeight() / imageInfo.get(i).getImageWidth() >= 2;
            if (ifLong) {
                type = "长图";
                Log.i(TAG, "长图判断" + imageInfo.get(i).getImageHeight() + " " + imageInfo.get(i).getImageWidth() + type);
            }
            imageView.setImgType(type);

        }
        mImageInfo = imageInfo;
        requestLayout();
    }

    /**
     * 获得 ImageView 保证了 ImageView 的重用
     */
    private ImageView getImageView(final int position) {
        ImageView imageView;
        if (position < imageViews.size()) {
            imageView = imageViews.get(position);
        } else {
            imageView = mAdapter.generateImageView(getContext());
            final String image=imageView.getDrawable().toString();
            //九宫格点击事件 imageView
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i(TAG,"图片视图"+image);
                    mAdapter.onImageItemClick(getContext(), NineGridView.this, position, mAdapter.getImageInfo());
                }
            });
            imageViews.add(imageView);
        }
        return imageView;
    }

    /**
     * 设置宫格间距
     */
    public void setGridSpacing(int spacing) {
        gridSpacing = spacing;
    }

    /**
     * 设置只有一张图片时的宽
     */
    public void setSingleImageSize(int maxImageSize) {
        singleImageSize = maxImageSize;
    }

    /**
     * 设置只有一张图片时的宽高比
     */
    public void setSingleImageRatio(float ratio) {
        singleImageRatio = ratio;
    }

    /**
     * 设置最大图片数
     */
    public void setMaxSize(int maxSize) {
        maxImageSize = maxSize;
    }

    public int getMaxSize() {
        return maxImageSize;
    }

    public static void setImageLoader(ImageLoader imageLoader) {
        mImageLoader = imageLoader;
    }

    public static ImageLoader getImageLoader() {
        return mImageLoader;
    }

    public interface ImageLoader {
        /**
         * 九宫格小图加载方法
         * 需要子类实现该方法，以确定如何加载和显示图片
         *
         * @param context   上下文
         * @param imageView 需要展示图片的ImageView
         * @param url       图片地址
         * @param width
         * @param height
         */
        void onDisplayImage(Context context, ImageView imageView, String url, int width, int height);

        /**
         * 九宫格小图加载方法,长图裁剪
         * 需要子类实现该方法，以确定如何加载和显示图片
         *
         * @param context   上下文
         * @param imageView 需要展示图片的ImageView
         * @param url       图片地址
         * @param width
         * @param height
         * @param cut
         */
        void onDisplayImage(Context context, ImageView imageView, String url, int width, int height, int cut);

        /**
         * 需要子类实现该方法，以确定如何加载和显示图片
         *
         * @param context   上下文
         * @param imageView 需要展示图片的ImageView
         * @param url       图片地址
         */
        void onDisplayImage(Context context, ImageView imageView, String url);


        /**
         * 加载长图
         *
         * @param context   上下文
         * @param imageView 长图控件
         * @param url       图片地址
         */
        void onDisplayImage(Context context, SubsamplingScaleImageView imageView, String url);


        /**
         * @param url 图片的地址
         * @return 当前框架的本地缓存图片
         */
        Bitmap getCacheImage(String url);
    }
}
